package com.ruoyi.common.DataConversion.controller;


import com.ruoyi.common.DataConversion.domain.DeviceParam;
import com.ruoyi.common.DataConversion.domain.DeviceTCP;
import com.ruoyi.common.DataConversion.service.DeviceParameterMonitoringService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.electronicFence.domain.TDeviceInfoModificationHistory;
import com.ruoyi.electronicFence.service.ITDeviceInfoModificationHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


/**
 * 监测设备详情编辑和下发监测设备的TCP通讯参数
 * @Description 该控制器用于编辑和下发监测设备的TCP通讯参数。通过该控制器，可以配置和管理监测设备与服务器之间的TCP连接参数，确保设备能够稳定地与服务器进行通信。
 * @Author ygsj
 * @Date 2024-10-17 17:11
 * @Version 1.0.0.0
 **/
@RestController
@CrossOrigin
@RequestMapping("/electronicFence/parameterInfo")
public class DeviceParameterMonitoringController extends BaseController {

    @Autowired
    private DeviceParameterMonitoringService deviceParameterMonitoringService;
    @Autowired
    private ITDeviceInfoModificationHistoryService deviceInfoModificationHistoryService;

    /**
     * 读取单个基本信息
     * Read single basic information
     *
     * @param param 请求参数，包括站ID和起始地址
     *              Request parameters, including station ID and start address
     * @return 操作结果
     *         Operation result
     */
    @PostMapping(value = "/readStationSingleParam", produces = "application/json;charset=UTF-8")
    public AjaxResult readStationSingleParam(@RequestBody HashMap<String, Object> param) {
        try {
            // 设置站ID
            // Set station ID
            param.put("StationID", "1");

            // 从请求参数中获取起始地址，并转换为整数
            // Get the start address from request parameters and convert it to an integer
            int startAddress = Integer.parseInt((String) param.get("startAddress"));

            // 将起始地址转换为16进制字符串
            // Convert the start address to a hexadecimal string
            String addressHex = Integer.toHexString(startAddress);

            // 创建设备TCP对象，并设置起始地址
            // Create a DeviceTCP object and set the start address
            DeviceTCP deviceTCP = new DeviceTCP();
            deviceTCP.setAddress(startAddress);

            // 调用服务方法读取站点参数
            // Call the service method to read station parameters
            Map<String, Object> stationMap = deviceParameterMonitoringService.readStationParam(
                    param.get("StationID").toString(),
                    addressHex,
                    4,
                    deviceTCP
            );


            // 返回操作成功的结果
            // Return the result of successful operation
            return success(stationMap);

        } catch (Exception ex) {
            // 打印异常堆栈信息
            // Print the exception stack trace
            ex.printStackTrace();

            // 返回操作失败的结果
            // Return the result of failed operation
            // return error(AjaxResult.Type.ERROR, CommonEnum.OPERATION_EXCEPTION, null);
            return null;
        }
    }



    /**
     * 读取读取单个基本信息V2
     * Read single basic information
     *
     *              Request parameters, including station ID and start address
     * @return 操作结果
     *         Operation result
     */
    @PostMapping(value = "/readDeviceParameter", produces = "application/json;charset=UTF-8")
    public AjaxResult readStationParam( @RequestBody DeviceParam deviceParam) {
        try {

            //名称转为对应的地址字符串
            String startAddressStr = getStartAddress(deviceParam.getDeviceParamName());

            int startAddress = Integer.parseInt(startAddressStr);

            // 将起始地址转换为16进制字符串
            // Convert the start address to a hexadecimal string
            String addressHex = Integer.toHexString(startAddress);

            // 创建设备TCP对象，并设置起始地址
            // Create a DeviceTCP object and set the start address
            DeviceTCP deviceTCP = new DeviceTCP();
            deviceTCP.setAddress(startAddress);

            // Call the service method to read station parameters
            Map<String, Object> stationMap = deviceParameterMonitoringService.readStationParam(
                    deviceParam.getDeviceIp(),
                    addressHex,
                    4,
                    deviceTCP
            );
            // 返回操作成功的结果
            // Return the result of successful operation
            return success(stationMap);

        } catch (Exception ex) {
            // 打印异常堆栈信息
            // Print the exception stack trace
            ex.printStackTrace();

            // 返回操作失败的结果
            // Return the result of failed operation
            // return error(AjaxResult.Type.ERROR, CommonEnum.OPERATION_EXCEPTION, null);
            return null;
        }
    }



    /**
     * 写单个基本信息
     *
     * @return
     */
    @PostMapping(value = "/writeDeviceParameter", produces = "application/json;charset=UTF-8")
    public AjaxResult writeStationParam(@RequestBody  DeviceParam deviceParam) {
        try {
            String deviceParamName = deviceParam.getDeviceParamName();
            String deviceParamValue = deviceParam.getDeviceParamValue();
            //记录修改历史
            recordUpdateHistory(deviceParam);

            if (deviceParamName.equals("检修模式")){

                if (deviceParamValue.equals("开启")){
                    deviceParamValue="85";
                }else if(deviceParamValue.equals("关闭")){
                    deviceParamValue="170";
                }
            }else {
                if (!deviceParamName.equals("最小限制人数") && !deviceParamName.equals("最大限制人数")) {
                    // 解析字符串为 double
                    double value = Double.parseDouble(deviceParamValue);
                    // 扩大十倍并转换为 int
                    int intValue = (int) (value * 10);
                    deviceParamValue = String.valueOf(intValue);
                }


            }

            //名称转为对应的地址字符串
            String startAddressStr = getStartAddress(deviceParamName);

            int startAddress = Integer.parseInt(startAddressStr);
            // 将起始地址转换为16进制字符串
            // Convert the start address to a hexadecimal string
            String addressHex = Integer.toHexString(startAddress);
            Map<String, Object> cardReaderMap = deviceParameterMonitoringService.writeStationParam(deviceParam.getDeviceIp(),
                        addressHex
                    , Integer.parseInt(deviceParamValue));
            return success(cardReaderMap);
        } catch (Exception ex) {
            ex.printStackTrace();
            return error();
        }

    }

    // 根据设备参数名称获取起始地址 十进制
    public String getStartAddress(String deviceParamMonitor) {
        String startAddressStr = "";
        switch (deviceParamMonitor) {
            case "报警区范围":
                startAddressStr = "8";
                break;
            case "司机区范围":
                startAddressStr = "12";
                break;
            case "断电区范围":
                startAddressStr = "20";
                break;
            case "最大限制人数":
                startAddressStr = "24";
                break;
            case "最小限制人数":
                startAddressStr = "28";
                break;
            case "检修模式":
                startAddressStr = "2056";
                break;
            default:
                throw new IllegalArgumentException("未知的设备参数名称: " + deviceParamMonitor);
        }
        return startAddressStr;
    }

    private void recordUpdateHistory(DeviceParam deviceParam){
        String deviceParamValueBeforeModified = deviceParam.getDeviceParamValueBeforeModified();
        String deviceParamName = deviceParam.getDeviceParamName();
        String deviceParamValue = deviceParam.getDeviceParamValue();

        if (deviceParamValueBeforeModified != null && deviceParamValue != null && !deviceParamValue.equals(deviceParamValueBeforeModified))
        {
            TDeviceInfoModificationHistory deviceInfoModificationHistory = new TDeviceInfoModificationHistory();
            deviceInfoModificationHistory.setDeviceId("")
                    .setDeviceName(deviceParam.getDeviceName())
                    .setDeviceIp(deviceParam.getDeviceIp())
                    .setParameterOfModification(deviceParamName)
                    .setTransportProtocol("TCP")
                    .setValueBeforeModification(deviceParamValueBeforeModified)
                    .setValueAfterModification(deviceParamValue)
                    .setTimeOfModification(LocalDateTime.now())
                    //.setUserOfModification("admin");
                    .setUserOfModification(SecurityUtils.getUsername());
            // 插入修改记录到数据库
            deviceInfoModificationHistoryService.insertTDeviceInfoModificationHistory(deviceInfoModificationHistory);

        }
    }
//

}
